package cloud.forms;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import cloud.beans.Review;
import cloud.dao.ReviewDao;

public final class ReviewForm extends Form{

	private static final String CHAMP_USERNAME = "userName";
	private static final String CHAMP_SCORE = "score";
	private static final String CHAMP_REVIEW = "review";
	private static final String CHAMP_ANIMEID = "anime_id";

	private ReviewDao reviewDao;
	private Review review;
	
	public ReviewForm() {
		
		super();
		this.reviewDao = new ReviewDao();
		this.review = new Review();
	}
	
	
	public Review createReview( HttpServletRequest request ) {
	
		String userName = getValeurChamp( request, CHAMP_USERNAME );
		int score = Integer.valueOf(getValeurChamp( request, CHAMP_SCORE ));
		String review = getValeurChamp( request, CHAMP_REVIEW );
		long anime_id = Long.valueOf( request.getParameter(CHAMP_ANIMEID));

		
		try {
			validationChampRequis(userName);
		}
		catch ( Exception e ) {
			setErreur( CHAMP_USERNAME, e.getMessage() );
		}
		this.review.setUserName(userName);
		
		try {
			validationChampRequis(getValeurChamp( request, CHAMP_SCORE ));
		}
		catch ( Exception e ) {
			setErreur( CHAMP_SCORE, e.getMessage() );
		}
		this.review.setScore(score);
		
		
		try {
			validationChampRequis(getValeurChamp( request, CHAMP_REVIEW ) );
		}
		catch ( Exception e ) {
			setErreur( CHAMP_REVIEW, e.getMessage() );
		}
		this.review.setReview(review);
		
		
		this.review.setDate(new Date());
		this.review.setAnime_id(anime_id);
			
		if ( this.erreurs.isEmpty() ) {
			if (this.reviewDao.creer(this.review)) {
				resultat = "Success.";
			}	
			else {
				setErreur(null, "Error.");
				this.resultat = "Technical Error.";
			}
		} 
		else {
			this.resultat = "Error.";
		}

		return this.review;
	}
	
	public List<Review> getList( long id ) {
		
		// Récuperation de la liste des codes en fonction de la rubrique
		List<Review> reviews = reviewDao.lister( id );

		// Si la recherche retourne un resultat
		if ( reviews != null && !reviews.isEmpty() ) {
			resultat = "Liste récupérée.";
		}
		
		return reviews;
	}
}